package cn.kgc.reflect;

import java.lang.reflect.Constructor;

/**
 * @author: mosin
 * @version: v1.0  2022/10/20
 * 通过反射操作类对象中的构造方法
 *  创建对象
 */
public class ReflectDemo03 {

    public static void main(String[] args) {

        try {

            Class  clazz = Class.forName("cn.kgc.reflect.User");
            // 获取类中所有的构造方法 Constructor  构造方法对象
            Constructor[] constructors = clazz.getConstructors();
            for (Constructor constructor : constructors) {
                System.out.println("constructor = " + constructor);
            }

            System.out.println("---------------getConstructor()--------------------");
            // 获取无参构造方法
            Constructor constructor = clazz.getConstructor();
            System.out.println("constructor = " + constructor);

            //   通过反射创建对象   newInstance()  参数是不定参  ...
            User user = (User) constructor.newInstance();
            System.out.println("user = " + user);

            System.out.println("---------------getConstructor(Integer.class,String.class)--------------------");
            //获取有参构造
            constructor = clazz.getConstructor(Integer.class,String.class);
            System.out.println("constructor = " + constructor);

            Object usr = constructor.newInstance(20, "tom");
            System.out.println("usr = " + usr);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }





}
